#include "StdAfx.h"
#include "resource.h"

#include "waconsts.h"
#include "eeg_exceptions.h"
#include "datastore.h"
#include "waitbox.h"
#include "dsacalculator.h"
#include "utilities.h"
#include "DSASingleGraph.h"



void DSASingleGraph::Draw(Graphics *g){
	//Bitmap bmp(rect.Width,rect.Height);//memory bitmap
	if(!buf){
		FontFamily   fontFamily(TEXT_FONT);
		StringFormat stringFormat;
		Font         font1(&fontFamily, AXIS_TEXT_SIZE/2, FontStyleBold, UnitPoint);
		Font         font2(&fontFamily, TEXT_SIZE, FontStyleBold, UnitPoint);
		buf = new BMPBuffer();
		buf->signiture = des.signiture;
		buf->bmp = new Bitmap(rect.Width,rect.Height);
		Graphics* graph = Graphics::FromImage(buf->bmp);
		//graph->Clear(Color(0,0,0));

		const int SR=calc->GetSource()->GetSamplingRate();

		const int graphWidth=rect.Width-2*MARGIN_WIDTH/*-MARGIN_WIDTH-DSA_SMALL_MARGIN*/;
		const int graphHeight=rect.Height-DSA_GRAPH_GAPWIDTH/*-2*DSA_SMALL_MARGIN*/;
		const int indexInOut = calc->FindInOut(des.signiture);
		const DSAOutput *out = calc->GetOutputs()[indexInOut];
		const unsigned int N=out->endpt - out->startpt;

		const UINT duration = N/SR;
		const UINT COUNT =DSA_MAX_FREQ*DSA_WINDOW_WIDTH; /*output_fftfreq2point(DSA_MAX_FREQ,SR,N/duration/DSA_WINDOW_WIDTH);*/

		const double wPerDot=graphWidth/(duration-1.0);
		const double hPerDot=graphHeight/(COUNT-1.0);

		for(UINT i=0;i<duration-1;i++){//time
			for(UINT j=1;j<(UINT)(COUNT);j++)//freq
			{
				double x = MARGIN_WIDTH+wPerDot*i;
				double y = hPerDot*(j-1);
				double r,g,b;
				HSLtoRGB(80+160*out->data[i][j]/out->max , 240 , 120 , &r , &g , &b );
				SolidBrush sb(Color(r,g,b));
				graph->FillRectangle(&sb,RectF(x,y,wPerDot,hPerDot));
			}
		}

		TCHAR buf[256];

		int x=MARGIN_WIDTH + graphWidth + DSA_GRAPH_GAPWIDTH;
		graph->DrawLine (new Pen(Color(255,255,255)) , x,0, x, graphHeight);
		for(int i = 0;i<=AXIS_SEGMENT;i++){

			int y=(graphHeight/AXIS_SEGMENT)*i;
			graph->DrawLine(new Pen(Color(255,255,255)),x,y,x+5,y);
			swprintf(buf,256,L"%.1lf",DSA_MAX_FREQ/AXIS_SEGMENT*(double)i);
			graph->DrawString(buf,-1,&font1,PointF(x+10 ,y),new SolidBrush(Color(255,255,255)));
		}


		//draw title
		graph->DrawString(des.title, -1, &font2, PointF(MARGIN_WIDTH/4.0,graphHeight/4.0), new SolidBrush(Color(255,255,255)));
		SAFE_DELETE( graph);
	}
	g->DrawImage(buf->bmp ,rect);
}
